package mvc.controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import bean.entity.User;
import jakarta.servlet.http.HttpSession;
import service.UserService;
import spring.SpringContextUtil;

@Controller
public class UserController {
	public UserController() {
		// TODO Auto-generated constructor stub
		System.out.println("User Controller started");
	}
	
	@GetMapping("/login")
	public String load(HttpSession session) {
		System.out.println("Come to Login Page");
		if (session.getAttribute("uid") == null) {
			return "login";
		}
		return "redirect:store";
	}

	@PostMapping("/loginsubmit")
	public String loginSubmit(@RequestParam("name") String name , @RequestParam("password")String password, HttpSession session) {
		System.out.println("User request to Login");
		
		UserService us = (UserService)SpringContextUtil.getBean("userService");
		
		var uid = us.validate(name, password);
		if (uid == null) {
			return "redirect:login";
		}
		
		session.setAttribute("name", name);
		session.setAttribute("uid", uid);
		session.setAttribute("balance", us.getUser(name).getBalance());
		return "redirect:store";
	}
	
	@GetMapping("/register")
	public String register() {
		return "register";
	}
	
	@PostMapping("/registersubmit")
	public String registerSubmit(
			@RequestParam("name")String name , @RequestParam("password") String password , @RequestParam("email") String email ,
			HttpSession session
			)
	{
		UserService us = (UserService) SpringContextUtil.getBean("userService");
		User user = new User(
					name.charAt(0) + String.valueOf(  System.currentTimeMillis()) ,
					name,
					password,
					email
				);
		if (us.register(user) != null) {
			return "redirect:login";
		}
		return "register";
	}
	
	@GetMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:store";
	}	
}
